import os
import time
import random
import re
import pandas as pd
import logging

# from sales_gpt import SalesGPT
from langchain.chat_models import ChatOpenAI
from langchain.llms.openai import OpenAI, OpenAIChat
from langchain.llms.base import LLM
from typing import Optional, List, Mapping, Any
import requests
from gpt_user import GptUser
from select_list import career_list,marriage_list


from bot.insurance_sales_gpt.demo.cache_dict import cache_dict
from bot.insurance_sales_gpt.data.gpt4 import get_user_info
from bot.insurance_sales_gpt.data.gpt4 import inference_user_info
from bot.insurance_sales_gpt.demo.user_job import UserJob

os.environ['OPENAI_API_KEY'] = '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' # fill me in

llm = OpenAIChat(temperature=0, model_name="gpt-3.5-turbo")


import csv
#写入标注数据
def write_data(strs):
    # 打开文件并创建一个CSV写入器
    with open('output/data_all.csv', 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 写入数据行
        writer.writerow(strs)

def init_user_info(session_id,age,sex,city):
    conversation_history = []
    user_job = {"家庭责任目标": "暂时未推理出目标", "个人健康目标": "暂时未推理出目标"}
    user_name=random.choice(["张", "李", "王", "赵"])
    user_sex = '先生' if sex==1 else '女士'
    user_age = age
    user_city = city
    user_info = {"name": user_name, "gender": user_sex, "age": user_age, "city": user_city,
                       "profession":"未提取到", "marriage": "未提取到", "income": "未推理出来",
                       "child_age": "未提取到"}
    is_kaichang = 1
    is_transfer = 0
    cache_dict[session_id] = {"user_info": user_info, "user_job": user_job,
                              "conversation_history": conversation_history,
                              "is_kaichang": is_kaichang, "is_transfer": is_transfer}

# def init_cache_content(self, session_id):
#     self.user_info["session_id"] = session_id
#     cache_dict[session_id] = {"user_info": user_info, "user_job": self.user_job,
#                                    "conversation_history": self.conversation_history,
#                                    "is_kaichang": self.is_kaichang, "is_transfer": self.is_transfer}

def update_user_info(session_id=None, lst=[]):
    for entity in lst:
        if entity.startswith('职业:'):
            career_entity = entity.split(':')[1]
            cache_dict[session_id]["user_info"]["profession"] = career_entity
        if entity.startswith('婚育:'):
            marriage_child_entity = entity.split(':')[1]
            cache_dict[session_id]["user_info"]["marriage"] = marriage_child_entity
        if entity.startswith('年收入:'):
            income_entity = entity.split(':')[1]
            cache_dict[session_id]["user_info"]["income"] = income_entity
        if entity.startswith('孩子年龄:'):
            child_age_entity = entity.split(':')[1]
            cache_dict[session_id]["user_info"]["child_age"] = child_age_entity
    print("now updated user_info is:{}".format(cache_dict[session_id]["user_info"]))



def format_DM_res(resp):
    resp = resp.replace(" ", "")
    idx_1 = resp.find('||')
    idx_2 = resp.find('#@')
    if idx_2 != -1 and idx_2 > idx_1 + 2:
        tmp1 = resp[idx_1 + 2:idx_2]
        idx_1 = resp.find('||', idx_2)
        idx_2 = resp.rfind('#@', idx_1)
        if idx_2 != -1 and idx_2 > idx_1 + 2:
            tmp2 = resp[idx_1 + 2:idx_2]
            resp = tmp1 + ' ' + tmp2
        else:
            resp = tmp1
    resp = resp.strip()
    return resp



df1=pd.read_excel("sources/黑牛均分不问收入1call-0524-614.xlsx")
print(df1.shape)
df2=pd.read_excel("sources/黑牛均分不问收入1call-0524-dm_record614.xlsx")
print(df2.shape)

huashu_simple=pd.read_csv("output/zx_huashu_simple.csv",header=None)
print(huashu_simple.shape,huashu_simple.columns)
huashu_simple_dict=dict(zip(huashu_simple[0],huashu_simple[2]))


# for i in range(10):
for i in range(287, df1.shape[0]+1):
    s=df1.iloc[i,:]
    dm_session_id=s['dm_session_id']
    age=s['age']
    sex=s['sex']
    city=s['city']
    dialogue_round=s['interactive_rounds']
    if dialogue_round<=3:
        print("轮次太少，skip")
        continue

    dialogue_df = df2[df2.session_id == dm_session_id].sort_values(by='msg_time').reset_index(drop=True)
    user_inputs=dialogue_df[dialogue_df['speaker_type']=='USER'].groupby('dialogue_round').agg({'msg_content':','.join}).msg_content.values.tolist()
    print("user_inputs:{}".format(user_inputs))
    sales_outputs=dialogue_df[dialogue_df['speaker_type']=='IVR'].groupby('dialogue_round').agg({'msg_content':','.join}).msg_content.values.tolist()
    print("sales_outputs:{}".format(sales_outputs))

    # sales_agent = SalesGPT.from_llm(llm, verbose=False,)
    # sales_agent.init_user_info(age,sex,city)
    # print("init new id:{},info:{}".format(id,sales_agent.user_info))
    init_user_info(dm_session_id,age,sex,city)


    # gpt_user=GptUser.from_llm(llm,verbose=True)
    rounds=1
    use_GPT=0
    while True:
        print("rounds:{}".format(rounds))
        # user
        if rounds>1:
            # user_input = input('Your response: ')
            # user_input = gpt_user._call(inputs={}, conversation_history='\n'.join(conversation_history), recent_sales_utterance=sales_responses,career_list=career_list,marriage_list=marriage_list)
            if len(user_inputs)>0:
                user_input =user_inputs.pop(0)
                user_input=re.sub(r'\[.*?\]', '', user_input)
            else:
                user_input = '用户挂机'
            # user_input = "用户: " + user_input
            conversation_history = cache_dict[dm_session_id].get("conversation_history", [])
            conversation_history.append("用户: " + user_input)
            cache_dict[dm_session_id]["conversation_history"] = conversation_history
        else:
            user_input=''

        print('user response:{}'.format(user_input))
        if use_GPT:
            user_info_extract = get_user_info(
                conversation_history='\n'.join(cache_dict[dm_session_id]["conversation_history"]),
                user_age=cache_dict[dm_session_id]["user_info"]["age"],
                user_gender=cache_dict[dm_session_id]["user_info"]["gender"],
                user_city=cache_dict[dm_session_id]["user_info"]["city"], )
            if user_info_extract:
                pattern = r"\[([^]]+)\]"
                matches = re.findall(pattern, user_info_extract)
                print("user_info_extract matches is {}".format(matches))
                if matches:
                    lst = [m.strip() for m in matches[0].split(",")]
                    print("lst is {}".format(lst))
                    update_user_info(dm_session_id, lst)
                #年收入推理
                user_income_extract = inference_user_info(user_age=cache_dict[dm_session_id]["user_info"]["age"],
                                                          user_gender=cache_dict[dm_session_id]["user_info"]["gender"],
                                                          user_city=cache_dict[dm_session_id]["user_info"]["city"],
                                                          user_marriage=cache_dict[dm_session_id]["user_info"]["marriage"],
                                                          user_career=cache_dict[dm_session_id]["user_info"]["profession"],)
                if user_income_extract:
                    print("user_income_extract matches is {}".format(user_income_extract))
                    lst = [user_income_extract]
                    print("lst is {}".format(lst))
                    update_user_info(dm_session_id, lst)

                # get user_job from user info
                cache_dict[dm_session_id]["user_job"] = UserJob(cache_dict[dm_session_id]["user_info"]).get_job()
                logging.info("user_job is {}".format(cache_dict[dm_session_id]["user_job"]))
                print("user_job is {}".format(cache_dict[dm_session_id]["user_job"]))
                now_user_job = cache_dict[dm_session_id]["user_job"]
                if now_user_job:
                    if now_user_job['家庭责任目标'] != '暂时未推理出目标' and now_user_job[
                        '个人健康目标'] != '暂时未推理出目标':
                        cache_dict[dm_session_id]["is_transfer"] = 1

        # sales_responses,sales_responses_tags,conversation_history,user_info,user_job=sales_agent.step(session_id=dm_session_id,query=user_input,sales_outputs=sales_outputs)
        if len(sales_outputs)>0:
            sales_responses_tags=sales_outputs.pop(0)
            sales_responses=format_DM_res(sales_responses_tags)
        else:
            sales_responses_tags,sales_responses='坐席挂机','坐席挂机'
        ai_message = "销售员" + "：" + sales_responses
        conversation_history = cache_dict[dm_session_id].get("conversation_history", [])
        conversation_history.append(ai_message)
        cache_dict[dm_session_id]["conversation_history"] = conversation_history
        print('sale huashu:{}'.format(sales_responses))

        #开始收集信息调用gpt4
        if '什么工作' in sales_responses or '孩子' in sales_responses or '结婚' in sales_responses:
            use_GPT=1

        if user_input:
            strs = [i, dm_session_id, '用户', user_input, cache_dict[dm_session_id]["user_info"], cache_dict[dm_session_id]["user_job"]]
            write_data(strs)
            if user_input=='用户挂机':
                break
            strs=[i,dm_session_id,'坐席',sales_responses,sales_responses_tags,huashu_simple_dict.get(sales_responses,sales_responses).strip('""""')]
            write_data(strs)
        else:
            strs = [i,dm_session_id,'坐席',sales_responses,sales_responses_tags,huashu_simple_dict.get(sales_responses,sales_responses).strip('""""')]
            write_data(strs)
        if '再见' in sales_responses or '转人' in sales_responses or '坐席挂机' in sales_responses:
            break
        time.sleep(1)
        rounds+=1